package com.kaily.timemanager.data.model;

import android.content.Context;

import com.app.common.db.Preferences.PreferencesStorage;
import com.kaily.timemanager.data.DataCallback;
import com.kaily.timemanager.data.DataListener;
import com.kaily.timemanager.data.contract.TaskContract;
import com.kaily.timemanager.db.AppCipDBManager;
import com.kaily.timemanager.db.AppDBManager;
import com.kaily.timemanager.db.AppLocalDataClient;
import com.kaily.timemanager.net.ApiClient;
import com.kaily.timemanager.obj.Task;
import com.kaily.timemanager.obj.TaskClass;
import com.kaily.timemanager.util.AppConstant;

import java.util.List;

import rx.Observable;
import rx.Subscriber;

/**
 * Created by zhoulikai on 2017/02/28
 */

public class TaskModelImpl implements TaskContract.Model {

    @Override
    public void getAllTask(final Context context, DataListener apiCallback) {
        if (context != null && apiCallback != null) {
            if (PreferencesStorage.getInstance(context).getValue(AppConstant.PREFERENCES_IS_TASK_NET, false)) {//网络上获取
                ApiClient.getInstance().request(ApiClient.getInstance().getApiStores().getTasks("gettask"),
                        new DataCallback<List<TaskClass>>(context, apiCallback, true));

            } else {//本地数据库读取
                AppLocalDataClient.getInstance(context).request(new Observable.OnSubscribe<List<TaskClass>>() {
                    @Override
                    public void call(Subscriber<? super List<TaskClass>> subscriber) {
                        List<TaskClass> taskClasses = AppDBManager.getInstance(context).getTaskClasses();
//                        if (taskClasses != null && !taskClasses.isEmpty()) {
//                            for (int i = 0; i < taskClasses.size(); i++) {
//                                TaskClass taskClass = taskClasses.get(i);
//                                if (taskClass != null) {
//                                    List<Task> tasks = AppCipDBManager.getInstance(context).getTasks(taskClass.getTaskClassId(), "0");
//                                    taskClass.setTasks(tasks);
//
//                                }
//
//                            }
//
//
//                        }
                        subscriber.onNext(taskClasses);
                        subscriber.onCompleted();

                    }
                }, new DataCallback<List<TaskClass>>(context, apiCallback, false));
            }

        }

    }

    @Override
    public void operationTaskClass(Context context, TaskClass taskClass, TaskContract.Presenter.TaskOp taskClassOp, DataListener dataListener) {

        if (context != null && taskClass != null && dataListener != null) {
            if (taskClassOp == TaskContract.Presenter.TaskOp.ADD) {
                AppDBManager.getInstance(context).addTaskClass(taskClass);
            }
        }

    }
}